import { defineStore } from 'pinia';
import axios from 'axios';

export const useUserStore = defineStore('user', {
  state: () => ({
    currentUser: null,
    token: '',
    isLoading: false,
    error: null,
    roles: []
  }),
  
  getters: {
    isAuthenticated: (state) => !!state.currentUser,
    userRole: (state) => state.currentUser?.role || null,
    getUserInfo: (state) => state.currentUser,
    getUserRoles: (state) => state.roles,
    hasRole: (state) => (role) => state.roles.includes(role)
  },
  
  actions: {
    async login(username, password) {
      this.isLoading = true;
      this.error = null;
      
      try {
        // 如果用户名为纯数字，作为患者ID登录
        if (/^\d+$/.test(username)) {
          const id = parseInt(username);
          const resp = await axios.get(`/api/patients/${id}`);
          const p = resp.data;
          if (!p || p.id === undefined) throw new Error('未找到该患者');
          const user = {
            id: p.id,
            username: `patient${p.id}`,
            role: 'patient',
            name: p.name || `患者${p.id}`,
            patientId: p.id,
            avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
          };
          const token = 'mock-jwt-token-' + Date.now();
          this.currentUser = user;
          this.token = token;
          this.roles = [user.role];
          localStorage.setItem('user', JSON.stringify(user));
          localStorage.setItem('token', token);
          return this.currentUser;
        }

        // 否则走示例账号（医生/患者）
        let user = null;
        if (username === 'doctor1' && password === '123456') {
          user = {
            id: 1,
            username: 'doctor1',
            role: 'doctor',
            name: '张医生',
            avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
          };
        } else if (username === 'patient1' && password === '123456') {
          user = {
            id: 1,
            username: 'patient1',
            role: 'patient',
            name: '李患者',
            patientId: 1,
            avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
          };
        } else {
          throw new Error('用户名或密码错误');
        }
        
        const token = 'mock-jwt-token-' + Date.now();
        
        // 设置状态
        this.currentUser = user;
        this.token = token;
        this.roles = [user.role];
        
        // 保存到本地存储
        localStorage.setItem('user', JSON.stringify(user));
        localStorage.setItem('token', token);
        
        return this.currentUser;
      } catch (error) {
        this.error = error.message;
        throw error;
      } finally {
        this.isLoading = false;
      }
    },
    
    logout() {
      this.currentUser = null;
      this.token = '';
      this.roles = [];
      localStorage.removeItem('user');
      localStorage.removeItem('token');
    },
    
    checkAuth() {
      const user = localStorage.getItem('user');
      const token = localStorage.getItem('token');
      
      if (user && token) {
        try {
          this.currentUser = JSON.parse(user);
          this.token = token;
          this.roles = this.currentUser.role ? [this.currentUser.role] : [];
        } catch (error) {
          console.error('恢复用户状态失败:', error);
          this.logout();
        }
      }
    },
    
    updateUserInfo(updates) {
      if (this.currentUser) {
        this.currentUser = { ...this.currentUser, ...updates };
        localStorage.setItem('user', JSON.stringify(this.currentUser));
      }
    }
  }
});